<template>
	<view>
		<view class="flex padding justify-around">
			<view 
				v-for="(item,index) in tabArr" 
				:class="{'text-gray':index!=tabIdx}" 
				@click="handleTab(index)"
			>
				{{item.name}}
			</view>
		</view>
		<view class="cake-list-cont flex flex-wrap justify-between">
			<!-- <cake-item></cake-item> -->
			<cake-item v-for="item in cakelist" v-bind:gdata="item"></cake-item>
		</view>
		<good-spec></good-spec>
	</view>
</template>

<script>
	import CakeItem from '../../components/cake-item.vue'
	import {
		$http
	} from '../../utils/http.js'
	import {
		cakeGet
	} from '../../api/cake.js'
	export default {
		data() {
			return {
				cakelist: [],
				tabArr: [{
						name: '蛋糕',
						bcid: 1
					},
					{
						name: '面包',
						bcid: 11
					},
					{
						name: '小食',
						bcid: 6
					},
					{
						name: '配件',
						bcid: 5
					},
				],
				tabIdx: 0,
				page:0
			};
		},
		components: {
			'cake-item': CakeItem
		},
		onLoad() { //页面vue文件中，需要使用onLoad
			this.fetchData()
		},
		methods:{
			handleTab(idx){
				this.tabIdx = idx
				this.refreshData()
			},
			fetchData(){  //请求方法封装
				let {tabArr,tabIdx,page,cakelist} = this
				let {bcid} = this.tabArr[tabIdx]
				cakeGet(bcid,page).then(res => {
					uni.stopPullDownRefresh() //关闭刷新动画
					let {results} = res.data
					if(results.length){
						this.cakelist = [
							...cakelist, //原数据
							...results //新数据
						]
						this.page++
						return
					}
					uni.showToast({
						title:'已经触达了底线~',
						icon:'none'
					})
				})
			},
			refreshData(){  //重置数据
				this.page = 0
				this.cakelist = []
				this.fetchData()
			}
		},
		onReachBottom() {  
			console.log('触底了');
			this.fetchData()
		},
		onPullDownRefresh() {
			console.log('下拉刷新');
			this.tabIdx = 0
			this.refreshData()
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #fff;
	}

	.cake-list-cont {
		padding: 15upx;
	}
</style>
